﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using HtmlAgilityPack;
using System.Windows.Forms;

namespace OrderAggregator.InputFormats.HyperOmsk
{
    /// <summary>
    /// Парсер заявок от Гипермаркет Омск
    /// </summary>
    public class HyperOmskFormat : BaseOrderFormat
    {
        public readonly static HyperOmskFormat Instance = new HyperOmskFormat();

        private HyperOmskFormat()
        {
        }
       
        /// <summary>
        /// Parse
        /// </summary>
        /// <param name="filePath"></param>
        /// <param name="getStream"></param>
        /// <returns></returns>
        public override BaseOrder Parse(string filePath, Func<System.IO.Stream> getStream)
        {
            if (!string.Equals(System.IO.Path.GetExtension(filePath), dotRTF, StringComparison.InvariantCultureIgnoreCase))
            {
                return null;
            }

            string content;
            using (var reader = new StreamReader(getStream(), Encoding.Default))
            {
                content = reader.ReadToEnd();
            }

            string[] lines;

            using (var rtb = new RichTextBox())
            {
                rtb.WordWrap = false;
                rtb.Rtf = content;
                lines = rtb.Lines;
            }

            string number = string.Empty;
            DateTime date = DateTime.MinValue;
            string client = string.Empty;
            var countField = 0;
            var temp = 0;
            var lengthLines = lines.Length;           
            List<string[]> rowsData = null;

            for (var i = 0; i < lines.Length; i++)
            {
                if (countField < 3)
                {
                    #region //считываем значения из шапки

                    if (lines[i].Contains("Код. номер") && lengthLines > i + 1)
                    {
                        number = lines[++i];
                        countField++;
                    }
                    else
                    {
                        if (lines[i].Contains("Дата, время поставки") && lengthLines > i + 1)
                        {
                            if (DateTime.TryParse(lines[++i], out date))
                            {
                                countField++;
                            }
                        }
                        if (lines[i].Contains("Адрес поставки") && lengthLines > i + 1)
                        {
                            client = lines[++i];
                            countField++;
                        }
                    }

                    #endregion
                }
                else
                {
                    if (rowsData == null)
                    {
                        #region//ищем начало данных

                        if (lines[i].Contains("№ п/п") && lengthLines > i + 8)
                        {
                            if (lines[i + 1].Contains("Код поставляемого товара") &&
                                lines[i + 2].Contains("Конфигурация") &&
                                lines[i + 3].Contains("Наименование товара") &&
                                lines[i + 4].Contains("Количество") &&
                                lines[i + 5].Contains("Ед./изм.") &&
                                lines[i + 6].Contains("Цена/ед.(руб)") &&
                                lines[i + 7].Contains("Сумма (руб)")
                                )
                            {
                                rowsData = new List<string[]>();                               
                                i = i + 8;                               
                            }
                        }

                        #endregion
                    }
                    else
                    {                    
                        #region//считываем данные

                        if ((Int32.TryParse(lines[i], out temp)) && (temp == rowsData.Count +1)) 
                        {
                            rowsData.Add(new string[]{lines[i],
                                                lines[i + 1],
                                                lines[i + 2],
                                                lines[i + 3],
                                                lines[i + 4],
                                                lines[i + 5],
                                                lines[i + 6],
                                                lines[i + 7]
                                                }
                                        );

                            i = i + 8;
                        }
                        else
                        {
                            break;
                        }

                        #endregion
                    }
                }
            }

            if (countField < 3 || rowsData == null || rowsData.Count == 0)
            {
                return null;
            }

            var order = new BaseOrder();
            order.Id = number;
            order.Client = client;
            order.ReceiveTime = date;

            for (var i = 0; i < rowsData.Count; i++)
            {
                var orderRow = new BaseOrderRow();

                orderRow.ProductCode = rowsData[i][1];
                orderRow.ProductName = rowsData[i][3];
                orderRow.Count = decimal.Parse(rowsData[i][4], BaseOrderFormat.RuCulture);
                orderRow.UnitName = rowsData[i][5]; ;

                order.OrderRows.Add(orderRow);
            }

            return order;
        }
    }
}
